/*
 * MIT License
 *
 * Copyright (c) 2024-2048 冰羽
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

package cn.star.framework.core;

import cn.hutool.core.util.ReflectUtil;
import cn.star.framework.repository.JpaRepositoryFactoryBean;
import cn.star.framework.repository.SimpleJpaRepository;
import java.io.Serializable;
import javax.persistence.EntityManager;
import org.hibernate.Session;
import org.hibernate.query.internal.AbstractProducedQuery;
import org.hibernate.transform.ResultTransformer;
import org.springframework.aop.framework.Advised;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.data.repository.NoRepositoryBean;
import org.springframework.data.repository.query.QueryByExampleExecutor;

/**
 * Storage<br>
 * {@link JpaSpecificationExecutor} Support Specification Query<br>
 * {@link QueryByExampleExecutor} Support Example Query (QBE)<br>
 * <a
 * href='https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#repository-query-return-types'>Spring
 * data Jpa Support</a><br>
 *
 * @author zhaoweiping
 *     <p style='color: red'>Created on 2024-09-23 11:06:00
 * @since 3.0.0
 */
@NoRepositoryBean
public interface IRepository<T extends IEntity, Id extends Serializable>
    extends JpaRepository<T, Id>, JpaSpecificationExecutor<T>, QueryByExampleExecutor<T> {

  /**
   * 获取{@link EntityManager}<br>
   * 默认获取到{@link EntityManager}可能为空<br>
   *
   * <p>若要获取到{@link EntityManager}，则JpaRepositoryFactoryBean需要使用{@link
   * JpaRepositoryFactoryBean}，此时{@link IRepository}实现将会指向{@link SimpleJpaRepository}
   *
   * <pre>
   *   &#064;EnableJpaRepositories(
   *     value = {...},
   *     repositoryFactoryBeanClass = JpaRepositoryFactoryBean.class)
   *   public class SpringBootApplication {
   *     // ...
   *   }
   * </pre>
   *
   * <p>默认{@link EntityManager}为空是因为{@link IRepository}默认实现指向了{@link
   * org.springframework.data.jpa.repository.support.SimpleJpaRepository}，默认使用反射获取字段值获取
   *
   * <p><b style='color: yellow'>{@link EntityManager#createQuery(String)}</b><br>
   * 查询示例：支持HQL查询
   *
   * <pre>
   *   List&lt;IEntity&gt; list = em.createQuery(
   *      "select field from IEntity.class.getName field where field.id = :id",
   *      IEntity.class
   *    )
   *   .setParameter("id", "value")
   *   .getResultList();
   * </pre>
   *
   * 需要注意的是此类查询中的设置参数的方法{@link javax.persistence.Query#setParameter(String,
   * Object)}中设置到字段上面的数据的类型，类型还是和实体中字段的类型一致，若不一致则会出现异常：<br>
   * <span style='color: red'>org.springframework.dao.InvalidDataAccessApiUsageException: Parameter
   * value [x] did not match expected type ...</span>
   *
   * <p><b style='color: yellow'>{@link EntityManager#createNativeQuery(String)}</b><br>
   * 查询示例：支持原生SQL查询
   *
   * <pre>
   *    Query nativeQuery = em.createNativeQuery("select * from table t where t.id = :id");
   *    nativeQuery.setParameter("id", "value");
   *    // {@link AbstractProducedQuery} {@link ResultTransformer}
   *    nativeQuery.unwrap(AbstractProducedQuery.class).setResultTransformer(new ResultTransformer());
   *    // 此时的list中的内容由转换器{@link ResultTransformer}决定
   *    List list = nativeQuery.getResultList();
   * </pre>
   *
   * @return {@link EntityManager}
   */
  @Deprecated
  default EntityManager getEntityManager() {
    try {
      // Spring使用动态代理导致EntityManager不能正常获取
      if (this instanceof Advised) {
        Advised advised = (Advised) this;
        Object o = advised.getTargetSource().getTarget();
        if (o instanceof SimpleJpaRepository) {
          return ((SimpleJpaRepository<?, ?>) o).getEntityManager();
        } else {
          // org.springframework.data.jpa.repository.support.SimpleJpaRepository#em
          Object em = ReflectUtil.getFieldValue(o, "em");
          if (em instanceof EntityManager) {
            return (EntityManager) em;
          }
        }
      }
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
    throw new RuntimeException(
        "Not found, please set: "
            + EnableJpaRepositories.class.getName()
            + "#repositoryFactoryBeanClass = "
            + JpaRepositoryFactoryBean.class.getName()
            + ".class");
  }

  /**
   * 获取{@link Session}
   *
   * @return {@link Session}
   */
  @Deprecated
  default Session getSession() {
    return this.getEntityManager().unwrap(Session.class);
  }
}
